//
//  MedicineView.m
//  Pocket Doctor alpha version
//
//  Created by Sherif, Yin, Taylor, Jacob, Anna, Mike on 11-10-25.
//  Copyright (c) 2011 __Sytjam__. All rights reserved.
//
//Class Description: Displays the medicines added into the database and shows what type medication it is.
//                   Adding/Viewing/Deleting medicine can be achieved from here.
//
//Known Bugs: Can not add to log when deleting by swiping table.
//

#import "MedicineView.h"
#import "AddMedicine.h"
#import "MainMenu.h"

@implementation MedicineView

@synthesize add, back, medicineView, medicinelist, medicineIDlist, medicineTypeList, navigationBar, teach, teachArrow, bottomBar, editOrDone;
@synthesize am, mm, mv, aD;

int selectedMedicineID;

/*Go back to main menu*/
- (IBAction)goBack:(id)sender{
    //Go back to Main Menu
    MainMenu *mmObject = [[MainMenu alloc]initWithNibName:@"MainMenu" bundle:nil];
    self.mm = mmObject;
    [mmObject release];
    
    mm.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:mm animated:YES];
}

/*Choose to add medicine
 will take you to AddMedicine view*/
- (IBAction)addMedicine:(id)sender{

    AddMedicine *amObject = [[AddMedicine alloc]initWithNibName:@"AddMedicine" bundle:nil];
    self.am = amObject;
    [amObject release];
    
    am.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:am animated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

/*How many rows are there in table view*/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.medicinelist count];
}

/*Selecting a row in the Table view will display an actionsheet*/
- (void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger row = [indexPath row];
    selectedMedicineID = [[medicineIDlist objectAtIndex:row] intValue];
    
    [medicineView deselectRowAtIndexPath:indexPath animated:YES];
    
    AddMedicine *amObject = [[AddMedicine alloc]initWithNibName:@"AddMedicine" bundle:nil];
    self.am = amObject;
    [amObject release];
    
    am.editID = selectedMedicineID;
    
    am.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:am animated:YES];
    [am loadMedicineByID];
}

- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger row = [indexPath row];
    selectedMedicineID = [[medicineIDlist objectAtIndex:row] intValue];
    
    if ([editOrDone.title isEqualToString:@"Modify Medicine List"]){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Are you sure?" message:@"This action can not be undone" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
        [alert show];
        [alert release];
    }
    else{
        if (editingStyle == UITableViewCellEditingStyleDelete){
            sqlite3_stmt * statement;
            NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
            const char * query_stmt = [enforceForeignKey UTF8String];
            
            [self removeLocalNotifications:selectedMedicineID];
            
            NSString *deleteMedicine = [[NSString alloc]initWithFormat:@"DELETE FROM Medicine WHERE id = %d;", selectedMedicineID];
            
            query_stmt = [deleteMedicine UTF8String];
            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                sqlite3_step(statement);    
                
                NSDate *saveDate = [NSDate date];
                
                NSString *medicine_name = [medicinelist objectAtIndex:row];
                
                NSString *queryLogString = [[NSString alloc]initWithFormat:@"INSERT INTO MedicineLog (medicine_name, log_change, status, time) VALUES ('%@',' ', 'Deleted', '%@')", medicine_name, saveDate];                    
                
                query_stmt = [queryLogString UTF8String];
                if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                    sqlite3_step(statement);
                    if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                        sqlite3_finalize(statement);
                    }
                }
            }
            
            //add log message here (med name deleted at time)
            
            [self loadMedicineFromDB];
            
            
            //[medicinelist removeObjectAtIndex:indexPath.row];
            [medicineView reloadData];
        } 
        else{
            if (editingStyle == UITableViewCellEditingStyleInsert)
            {
                [medicinelist insertObject:@"Tutorial" atIndex:[medicinelist count]];
                [medicineView reloadData];
            }
        }
    }
}

- (IBAction) EditTable:(id)sender{

    if([[editOrDone title]isEqualToString:@"Done"])
    {
        [super setEditing:NO animated:YES];
        [medicineView setEditing:NO animated:YES];
        [editOrDone setTitle:@"Modify Medicine List"];
        [editOrDone setStyle:UIBarButtonItemStylePlain];
    }
    else{
        [super setEditing:YES animated:YES];
        [medicineView setEditing:YES animated:YES];
        [editOrDone setTitle:@"Done"];
        [editOrDone setStyle:UIBarButtonItemStyleDone];
    }
}

/*Remove all this later

//Action Sheet Function
//check if user wants to modify, remove or do nothing to the medicine chosen
// from the table view/
- (void) actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 1) // buttonIndex 0 = "Modify medicine"
    {
        
        AddMedicine *amObject = [[AddMedicine alloc]initWithNibName:@"AddMedicine" bundle:nil];
        self.am = amObject;
        [amObject release];
        
        am.editID = selectedMedicineID;
        
        am.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:am animated:YES];
        [am loadMedicineByID];
        
    }
    else
        if(buttonIndex == 0)// buttonIndex 0 = "Remove medicine"
        { // todo: make executing a query a reusable method instead of duplicating code everywhere
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"This action can not be undone!" message:@"Are you sure?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
            
            [alert show];
            [alert release];
        }
}
*/

//Confirms deletion of medicine
//only if the swipe tableview action is done
//if Modify Medicine List button is pressed; this will not be asked.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    // the user clicked one of the OK/Cancel buttons
    /*
    if (buttonIndex == 1)
    {
        sqlite3_stmt * statement;
        NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
        const char * query_stmt = [enforceForeignKey UTF8String];
        
        [self removeLocalNotifications:selectedMedicineID];
        
        NSString *deleteMedicine = [[NSString alloc]initWithFormat:@"DELETE FROM Medicine WHERE id = %d;", selectedMedicineID];
        
        query_stmt = [deleteMedicine UTF8String];
        if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
            sqlite3_step(statement);    
            
            NSDate *saveDate = [NSDate date];
            
            NSString *medicine_name = [medicinelist objectAtIndex:row];
            
            NSString *queryLogString = [[NSString alloc]initWithFormat:@"INSERT INTO MedicineLog (medicine_name, log_change, status, time) VALUES ('%@',' ', 'Deleted', '%@')", medicine_name, saveDate];                    
            
            query_stmt = [queryLogString UTF8String];
            if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
                sqlite3_step(statement);
                if (sqlite3_errcode(aD.dbPointer) == SQLITE_DONE){
                    sqlite3_finalize(statement);
                }
            }
        }
        
        [self loadMedicineFromDB];
        
        
        //[medicinelist removeObjectAtIndex:indexPath.row];
        [medicineView reloadData];
     }*/
    
    if (buttonIndex==1) {
        [medicineView setEditing:YES animated:YES];
        [editOrDone setTitle:@"Done"];
        [editOrDone setStyle:UIBarButtonItemStyleDone];
    }
}

/*populates each cell in the table view*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:SimpleTableIdentifier] autorelease];
    }
    NSUInteger row = [indexPath row];
    
    cell.textLabel.text = [medicinelist objectAtIndex:row];
    cell.detailTextLabel.text = [medicineTypeList objectAtIndex:row];
    return cell;
}


#pragma mark - View lifecyclei

/*Load medicines from database so they can be populated into the table view*/
- (void)loadMedicineFromDB
{
    sqlite3_stmt * statement;
    NSString * enforceForeignKey = @"PRAGMA foreign_keys = 1";
    const char * query_stmt = [enforceForeignKey UTF8String];
    
    NSMutableArray *medicineListObject = [[NSMutableArray alloc] init];
    NSMutableArray *medicineIDListObject = [[NSMutableArray alloc] init];
    NSMutableArray *medicineTypeListObject = [[NSMutableArray alloc] init];

    NSString *addEntry = [[NSString alloc]initWithFormat:@"SELECT medicine_name, id, dosage_type FROM Medicine;"];
   
    query_stmt = [addEntry UTF8String];
    if (sqlite3_prepare_v2(aD.dbPointer, query_stmt, -1, &statement, NULL) == SQLITE_OK){
        
        while (sqlite3_step(statement) == SQLITE_ROW){
            [medicineListObject addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
            [medicineIDListObject addObject:[NSNumber numberWithInteger:sqlite3_column_int(statement, 1)]];
            [medicineTypeListObject addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)]];
        }
    }
    
    // NSArray *medicinelistObject = [[NSArray alloc] initWithObjects:@"Medicine 1", @"Medicine 2", @"Medicine 3", nil];
    
    self.medicineTypeList = medicineTypeListObject;
    self.medicinelist = medicineListObject;
    self.medicineIDlist = medicineIDListObject;
    
    [medicineTypeListObject release];
    [medicineListObject release];
    [medicineIDListObject release];
    

}

/*Functions to be done when the view is loaded
 this includes loading the database*/
- (void)viewDidLoad
{
    //Load TableView
    
    aD = [[UIApplication sharedApplication] delegate];
    
    [self loadMedicineFromDB];
 
    
    if(medicinelist.count != 0) {
        teachArrow.hidden = true;
        teach.hidden = true;
    }
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)removeLocalNotifications:(int) medicineID{
    NSArray * notiflist = [[UIApplication sharedApplication] scheduledLocalNotifications];
    NSEnumerator *e = [notiflist objectEnumerator];
    UILocalNotification * notification;
    while (notification = [e nextObject]) {
        NSNumber *ID = [notification.userInfo objectForKey:@"id"];
        if([ID intValue] == medicineID){
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
        }
    }
}

/*release outlets*/
- (void) dealloc{
    
    [mm release];
    [am release];
    [mv release];
    [aD release];
    
    [add release];
    [back release];
    [navigationBar release];
    [editOrDone release];
    [bottomBar release];
    [medicineView release];
    [teach release];
    [teachArrow release];
    [medicinelist release];
    [medicineIDlist release];
    [medicineTypeList release];
    
    [super dealloc];
}

@end
